package com.huarui.permission.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.ewaf.framework.service.BaseService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.permission.dao.PermissionDao;
import com.huarui.permission.dataobject.Permission;
import com.huarui.saleInvoice.util.SaleInvoiceMessageEnum;

public class PermissionManagerService extends BaseService {
	private final static Logger logger = Logger.getLogger(PermissionManagerService.class);
	private PermissionDao permissionDao;
	public Map<String,Object> save(final Permission permission){
		final Map<String,Object> resultMap=new HashMap<String, Object>();
		// 修改数据
		try {
			transactionTemplate.execute(new TransactionCallback() {

				@Override
				public Object doInTransaction(TransactionStatus status){
					if(permission.getId()==null){
						permission.setIsGroup(0);
						permissionDao.create(permission);
						if(permission.getParentId()!=0){
							Map<String,Object> map=new HashMap<String, Object>();
							map.put("id",permission.getParentId());
							Permission parent=(Permission) permissionDao.getById(map);
							if(parent.getIsGroup()==0){
								parent.setIsGroup(1);
								permissionDao.update(parent);
							}
						}
					}else{
						permissionDao.update(permission);
					}
					resultMap.put("permission", permission);
					return null;
				}
			});
		} catch (Exception e) {
			logger.error("保存权限出错",e);
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(), SaleInvoiceMessageEnum.ERROR_MSG_DATABASE.getMsg());
			return resultMap;
		}
		resultMapInfo(resultMap);
		return resultMap;
	}
	public Map<String,Object> delete(final Integer id){
		final Map<String,Object> resultMap=new HashMap<String, Object>();
		// 修改数据
		try {
			transactionTemplate.execute(new TransactionCallback() {

				@Override
				public Object doInTransaction(TransactionStatus status){
					boolean isUpdate=true;
					List<Permission> permissionList=permissionDao.getAllPermissions();
					Map<Integer,Permission> permissionsMap=new HashMap<Integer, Permission>();
					for(Permission obj:permissionList){
						permissionsMap.put(obj.getId(), obj);
					}
					Permission permission=permissionsMap.get(id);
					Integer pId=permission.getParentId();
					List<Integer> list=recursion(id,permissionsMap);
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("ids", list);
					permissionDao.deleteByCondition(map);
					for(Integer id:list){
						permissionsMap.remove(id);
					}
					for(Iterator it=permissionsMap.entrySet().iterator();it.hasNext();){
						Map.Entry e=(Entry) it.next();
						Permission obj=(Permission) e.getValue();
						Integer parentId=(Integer) obj.getParentId();
						if(parentId.intValue()==pId.intValue()){
							isUpdate=false;
							break;
						}
					}
					if(isUpdate){
						Permission updatePer=permissionsMap.get(pId);
						updatePer.setIsGroup(0);
						permissionDao.update(updatePer);
					}
					return null;
				}
			});
		} catch (Exception e) {
			logger.error("删除权限出错",e);
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(), SaleInvoiceMessageEnum.ERROR_MSG_DATABASE.getMsg());
			return resultMap;
		}
		resultMapInfo(resultMap);
		
		return resultMap;
	}
	
	private List<Integer> recursion(Integer id,Map<Integer,Permission> permissionsMap){
		List<Integer> parentList=new ArrayList<Integer>();
		parentList.add(id);
		List<Integer> resultList=new ArrayList<Integer>();
		this.genDelPremissionsId(permissionsMap, parentList,resultList);
		return resultList;
	}
	@SuppressWarnings("unchecked")
	public List<Integer> genDelPremissionsId(Map mapAll,List<Integer> list,List<Integer> resultList){
			for(Integer id:list){
				Permission permission=(Permission) mapAll.get(id);
				Integer isGroup=permission.getIsGroup();
				if(isGroup==1){
					List tempList=new ArrayList();
					for(Iterator it=mapAll.entrySet().iterator();it.hasNext();){
						Map.Entry e=(Entry) it.next();
						Permission obj=(Permission) e.getValue();
						Integer parentId=(Integer) obj.getParentId();
						if(parentId.intValue()==id.intValue()){
							tempList.add(obj.getId());
						}
					}
					//if(tempList.size()>0){
						genDelPremissionsId(mapAll,tempList,resultList);
					//}
				}else if(isGroup==0){
					mapAll.remove(id);
				}
				resultList.add(id);
			}
		return resultList;
	}
	
	
	public Map<String,Object> updateParent(final Integer id,final Integer oldParentId,final Integer newParentId){
		final Map<String,Object> resultMap=new HashMap<String, Object>();
		// 修改数据
		try {
			transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus status){
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("id", id);
					Permission permission=permissionDao.getById(map);
					permission.setParentId(newParentId);
					permissionDao.update(permission);
					if(oldParentId!=0){
						Map<String,Object> tempMap=new HashMap<String, Object>();
						tempMap.put("id",oldParentId);
						Permission parent=(Permission) permissionDao.getById(tempMap);
						tempMap.clear();
						tempMap.put("parentId", parent.getId());
						List<Permission> list=permissionDao.getPermissionListByCondition(tempMap);
						if(parent.getIsGroup()==1&&list.size()==0){
							parent.setIsGroup(0);
							permissionDao.update(parent);
						}
					}
					return null;
				}
			});
		} catch (Exception e) {
			logger.error("移动权限出错",e);
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(), SaleInvoiceMessageEnum.ERROR_MSG_DATABASE.getMsg());
			return resultMap;
		}
		resultMapInfo(resultMap);
		return resultMap;
	}
	
	private void resultMapInfo(Map<String,Object> resultMap){
		if(!resultMap.containsKey(SaleInvoiceMessageEnum.SUCCESS.getMsg())){
			resultMap.put(SaleInvoiceMessageEnum.SUCCESS.getMsg(),SaleInvoiceMessageEnum.RESULT_TYPE_SUCCESS.getMsg());
		}
	}
	public PermissionDao getPermissionDao() {
		return permissionDao;
	}
	public void setPermissionDao(PermissionDao permissionDao) {
		this.permissionDao = permissionDao;
	}
	
}
